import less from "less";
/**
 * @author 张维金
 * @date 2023-04-06 星期四
 * @function 根据颜色配置，生成0.1-1透明度颜色配置，并绑定到body上
 * @param {String} url
 */
class Index {
  constructor(url) {
    this.getData(url);
  }

  /**
   * @author 张维金
   * @date 2023-04-06 星期四
   * @function 获取css配置
   * @param {String} url
   */
  getData(url) {
    fetch(url)
      .then(r => r.text())
      .then(c => {
        c = c
          .replace(/\s/g, "") // 去除空
          .replace(/\/\*.+?\*\//g, "") // 去除注释
          .match(/--.+?:.+?;/g);
        // root变量
        let { lessCode, colorCode } = this.createRootCSS(c);

        this.jsToLess(`:root{${lessCode}}${colorCode}`);
      });
  }

  createRootCSS(c) {
    let lessCode = "";
    // 颜色,字体,边框,背景
    let colorCode = "";
    c.map(d => {
      let [key, value] = d.split(":");
      value = this.hexToRgb(value.slice(0, -1));
      for (let i = 0; i < 10; i++) {
        let name = `${key}${i == 9 ? "" : "-" + (i + 1)}`;
        let classNmae = `${key.replace(/--/, "")}${i == 9 ? "" : "-" + (i + 1)}`;
        let _value = value.replace(/1\)/, `${(i + 1) / 10})`);
        lessCode += `${name}:${_value};`;
        colorCode += `
        .color-${classNmae}{
          color:var(${name})
        };
        .bor-${classNmae}{
          border: 1px solid var(${name})
        };
        .bor2-${classNmae}{
          border: 2px solid var(${name})
        };
        .bg-${classNmae}{
          background-color:var(${name})
        };`;
      }
    });
    return { colorCode, lessCode };
  }

  /**
   * @author 张维金
   * @date 2023-04-06 星期四
   * @function hex颜色值转换为rgba
   * @param {String} hexValue 颜色值
   * @param {Number} opc 透明度 0-1
   * @return {}
   */
  hexToRgb(hexValue, opc = 1) {
    let rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    let hex = hexValue.replace(rgx, (_m, r, g, b) => r + r + g + g + b + b);
    let rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if (!rgb) return hexValue;
    return `rgba(${parseInt(rgb[1], 16)},${parseInt(rgb[2], 16)},${parseInt(rgb[3], 16)},${opc})`;
  }

  /**
   * @author 张维金
   * @date 2023-04-07 星期五
   * @function js生成less代码,并转化为css写入页面
   * @param {}
   * @return {}
   */
  jsToLess(code) {
    less
      .render(code)
      .then(c => {
        let style = document.createElement("style");
        style.setAttribute("type", "text/css");
        // console.log("c.css", c.css.replace(/\s/g, ""));
        style.innerHTML = c.css.replace(/\s/g, "").replace(/solid/g, " solid ");
        document.head.appendChild(style);
      })
      .catch(console.log);
  }
}

export default Index;
